const Client = require('ssh2-sftp-client')
const fs = require('fs')
const path = require('path')
const sftp = new Client()

const userConfig = {
  id_rsa_path: 'C:/Users/Administrator/.ssh/id_rsa',
  build_path: path.resolve('./stage'),
  upload_path: '/www/wwwroot/whs/whs_supplier',
}

const config = {
  host: '121.37.215.227',
  port: 22,
  username: 'root',
  privateKey: fs.readFileSync(userConfig.id_rsa_path, 'utf8'),
}

async function uploadDirectory() {
  try {
    await sftp.connect(config)
    console.log('已连接到服务器')

    // // 检查目标目录是否存在   不行宝塔有个源配置不能删,所以先用覆盖的看看
    // const exists = await sftp.exists(userConfig.upload_path)

    // if (exists) {
    //   console.log('目标目录已存在，正在删除...')
    //   // 递归删除目录中的所有内容
    //   await sftp.rmdir(userConfig.upload_path, true)
    //   console.log('目标目录已删除')
    // }

    // // 创建新的空目录
    // await sftp.mkdir(userConfig.upload_path, true)
    // console.log('已创建新的目标目录')

    // 上传整个目录
    const result = await sftp.uploadDir(
      userConfig.build_path,
      userConfig.upload_path
    )

    console.log('目录上传成功!')
    await sftp.end()
  } catch (err) {
    console.error('发生错误:', err)
    await sftp.end()
  }
}

uploadDirectory()
